package com.linkage.seapeak.activity.chat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.flexbox.FlexboxLayout;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.ApplyProNoticeActivity;
import com.linkage.jz.bankruptcy.activity.Project.CreateProjectDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.EditProjectDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQOneProjectActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.EditZQUserBaseInfoActivity;
import com.linkage.jz.bankruptcy.adapter.MyProListViewAdapter;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicLongNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.seapeak.base.BaseActivity;
import com.linkage.seapeak.utils.CommonUtils;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SearchProjectActivity extends BaseActivity implements BGAOnRVItemLongClickListener, BGAOnRVItemClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {

    //搜索隔断符号
    private String SPLIT_KEY_FLAG = "#￥";
    //搜索存储本地key
    private String SP_KEY = "proSearchKeys";

    private EditText editKeyword;
    private TextView cancel;
    private RecyclerView projectList;
    private FlexboxLayout recommendTips;
    private MyProListViewAdapter adapter;

    private PublicNoticeDialog noticeDialog;
    private PublicLongNoticeDialog noticelxDialog;

    private ShapeLoadingDialog shapeLoadingDialog;
    private View empty_layout;
    private View recommend_layout;

    List<MyProInfo> dataList;

    List<String> searchHistory = new ArrayList();

    int margin;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarMode(false);
        setContentView(R.layout.activity_search_project);
        initView();
        shapeLoadingDialog = new ShapeLoadingDialog(SearchProjectActivity.this);
        margin = CommonUtils.dp2px(SearchProjectActivity.this, 10);
        addSearchHistory();
    }

    /**
     * 添加热搜视图
     */
    private void addSearchHistory() {
        String historyStr = SPUtils.getInstance().getString(SP_KEY);
        recommendTips.removeAllViews();
        if (!TextUtils.isEmpty(historyStr)) {
            recommend_layout.setVisibility(View.VISIBLE);
            searchHistory = new ArrayList<>(Arrays.asList(historyStr.split(SPLIT_KEY_FLAG)));
        } else
            recommend_layout.setVisibility(View.GONE);

        for (final String key : searchHistory) {
            TextView textView = new TextView(SearchProjectActivity.this);
            textView.setBackgroundResource(R.drawable.border_666);
            textView.setTextSize(14);
            textView.setTextColor(0xff666666);
            textView.setText(key);
            textView.setPadding(margin, margin / 2, margin, margin / 2);
            FlexboxLayout.LayoutParams lp = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.leftMargin = margin;
            lp.topMargin = margin;
            lp.rightMargin = margin;
            textView.setLayoutParams(lp);
            recommendTips.addView(textView);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editKeyword.setText(key);
                    InputMethodManager imm = (InputMethodManager) editKeyword.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null)
                        imm.hideSoftInputFromWindow(editKeyword.getWindowToken(), 0);
                    getData();
                }
            });
        }
    }

    private void initView() {
        dataList = new ArrayList<>();
        editKeyword = (EditText) findViewById(R.id.edit_keyword);
        cancel = (TextView) findViewById(R.id.cancel);
        projectList = (RecyclerView) findViewById(R.id.project_item);
        recommendTips = (FlexboxLayout) findViewById(R.id.tips);
        recommend_layout = findViewById(R.id.recommend_layout);
        empty_layout = findViewById(R.id.empty_layout);
        projectList.setLayoutManager(new LinearLayoutManager(SearchProjectActivity.this));
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        editKeyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) editKeyword.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null)
                        imm.hideSoftInputFromWindow(editKeyword.getWindowToken(), 0);
                    getData();
                    return true;
                }
                return false;
            }
        });

        editKeyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(editKeyword.getText().toString())) {
                    addSearchHistory();
                    empty_layout.setVisibility(View.GONE);
                    if (dataList != null && dataList.size() > 0) {
                        dataList.clear();
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    recommend_layout.setVisibility(View.GONE);
                }
            }
        });

        adapter = new MyProListViewAdapter(projectList, SearchProjectActivity.this);

        adapter.setOnRVItemClickListener(this);
        adapter.setOnRVItemLongClickListener(this);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnItemChildLongClickListener(this);
        adapter.setData(dataList);
        projectList.setAdapter(adapter);
        projectList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    adapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
    }


    /**
     * 获取数据
     */
    public void getData() {
        String str = editKeyword.getText().toString();
        if (TextUtils.isEmpty(str)) {
            return;
        }

        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }

        if (!searchHistory.contains(str))
            searchHistory.add(0, str);
        String searchStr = "";
        for (String key : searchHistory) {
            searchStr += key;
            searchStr += SPLIT_KEY_FLAG;
        }
        SPUtils.getInstance().put(SP_KEY, searchStr);

        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("userToken", userToken)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("pageNumber", "1")
                .add("pageSize", "100")
                .add("keywords", str)
                .build();

        String url = Consts.WEBURL_SEARCHPRO;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                dataList.clear();
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject object = new JSONObject(str);
                            JSONObject objdata = object.getJSONObject("data");
                            MyProInfo[] array = new Gson().fromJson(objdata.optString("list"), MyProInfo[].class);
                            List<MyProInfo> list = Arrays.asList(array);
                            dataList.clear();
                            dataList.addAll(list);
                            adapter.notifyDataSetChanged();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            dataList.clear();
                            adapter.notifyDataSetChanged();
                        }

                        if (dataList == null || dataList.size() == 0)
                            empty_layout.setVisibility(View.VISIBLE);
                        else
                            empty_layout.setVisibility(View.GONE);
                    }
                });
            }
        });
    }

    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
        return true;
    }

    @Override
    public void onRVItemClick(ViewGroup parent, View v, int position) {
        try {
            if (position < adapter.getData().size()) {
                MyProInfo model = adapter.getItem(position);
                if (model != null) {
                    if(model.getAuth().getAllowJoin()) {
                        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
                        if ("".equalsIgnoreCase(userToken)) {
                            noticeDialog = new PublicNoticeDialog(SearchProjectActivity.this, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    switch (view.getId()) {
                                        case R.id.ll_close:
                                            noticeDialog.dismiss();
                                            break;

                                        case R.id.btn_chancel_notice:
                                            noticeDialog.dismiss();

                                            break;

                                        case R.id.btn_save_notice:
                                            RegisterActivity.start(SearchProjectActivity.this);
                                            noticeDialog.dismiss();
                                            break;

                                    }

                                }
                            }, 1, "提示", "操作此功能，需要请您先注册/登录",
                                    "取消", "确认");
                            noticeDialog.show();
                            return;
                        } else {
                            ApplyProNoticeActivity.start(SearchProjectActivity.this, model.getId(), model.getCreditorId(),
                                    model.getManagerId(), "管理人", model.getContactPhone());
                            return;
                        }

                    }

                    if (v.getId() == R.id.bt_item_bt1) {
                        if (model.getProjectColumnList().getFillingIn()) {
                            ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                            info.setBankruptcyProjectId(model.getId());
                            info.setId(model.getCreditorId());
                            CreateZQOneProjectActivity.start(SearchProjectActivity.this, info,model.getSysAddressId(), model.getContacts(),model.getContactPhone());
                            return;
                        }

                        if (model.getProjectColumnList().getContinueFillingIn()) {
                            getTempData(model.getCreditorId(),model.getId());
                            return;
                        }
                        if ("0".equalsIgnoreCase(model.getProjectStatus())) {
                            //删除 V

                            noticeDialog
                                    = new PublicNoticeDialog(SearchProjectActivity.this, new View.OnClickListener() {
                                @Override
                                public void onClick( View view ) {
                                    String  sendStatus = "";
                                    if (view.getId() == R.id.btn_chancel_notice) {//暂存
                                        sendStatus = "1";
                                        noticeDialog.dismiss();
                                    } else if (view.getId() == R.id.ll_close) {
                                        if (noticeDialog != null && noticeDialog.isShowing())
                                            noticeDialog.dismiss();
                                        return;
                                    } else {//生成
                                        sendStatus = "2";
                                        noticeDialog.dismiss();
                                        DelData(model.getId(), position);
                                    }

                                    noticeDialog.dismiss();

                                }
                            }, 1, "提示", "确定删除项目", "取消", "确定");
                            noticeDialog.show();

                        } else if ("1".equalsIgnoreCase(model.getProjectStatus())) {

                        } else if ("2".equalsIgnoreCase(model.getProjectStatus())) {

                            if (!"".equalsIgnoreCase(model.getJoinId()) && "0".equalsIgnoreCase(model.getJoinType()) && "0".equalsIgnoreCase(model.getAcceptInvitation())) {
                                //拒绝
                                noticeDialog = new PublicNoticeDialog(SearchProjectActivity.this, new View.OnClickListener() {
                                    @Override
                                    public void onClick( View view ) {
                                        String  sendStatus = "";
                                        if (view.getId() == R.id.btn_chancel_notice) {//暂存
                                            sendStatus = "1";
                                            noticeDialog.dismiss();
                                        } else if (view.getId() == R.id.ll_close) {
                                            if (noticeDialog != null && noticeDialog.isShowing())
                                                noticeDialog.dismiss();
                                            return;
                                        } else {//生成
                                            sendStatus = "2";
                                            noticeDialog.dismiss();
                                            accpectOrRefData(model.getId(), "2");
                                        }

                                        noticeDialog.dismiss();

                                    }
                                }, 1, "提示", "确定拒绝邀请?\n拒绝邀请后将导致无法线上申报债权、参与表决等操作！", "取消", "确定");
                                noticeDialog.show();

                            } else {
                                // 管理 V
                                Intent intent = new Intent(SearchProjectActivity.this, ProDetailActivity.class);
                                intent.putExtra("info", new Gson().toJson(model));
                                SearchProjectActivity.this.startActivity(intent);

                            }

                        } else if ("3".equalsIgnoreCase(model.getProjectStatus())) {
                        }

                    } else if (v.getId() == R.id.bt_item_bt2) {

                        if ("0".equalsIgnoreCase(model.getProjectStatus())) {
                            // 管理 V
//                CreateProjectDetailActivity.start(getActivity(), model, 2);
                            EditProjectDetailActivity.start(SearchProjectActivity.this, model, 2);

                        } else if ("1".equalsIgnoreCase(model.getProjectStatus())) {

                        } else if ("2".equalsIgnoreCase(model.getProjectStatus())) {

                            if (!"".equalsIgnoreCase(model.getJoinId()) && "0".equalsIgnoreCase(model.getJoinType()) && "0".equalsIgnoreCase(model.getAcceptInvitation())) {
                                //接收邀请
//                    noticeDialog = new PublicNoticeDialog(getActivity(), onClickListener,
//                            1, "重要须知", "为了保障债权人的合法权益，加入前请再次确认您是相关债权人本人或法定代表人，或是其代理人，并将以本手机号码 188997688976 注册的账户代表相关债权人进行操作，如须变更号码线上操作，请点击变更操作用户，填写操作人的手机号。您也可联系管理人，由管理人协助操作用户加入。",
//                            "确认加入", "变更操作用户");
//                    noticeDialog.show();
                                ApplyProNoticeActivity.start(SearchProjectActivity.this,model.getId(),model.getCreditorId(),model.getSysAddressId(), model.getContacts(),model.getContactPhone());
                            }

                            //需判断是不是自己项目
                            if (model.getCreator().equalsIgnoreCase(BankruptcyApp.loginInfo.getId())) {
                                EditProjectDetailActivity.start(SearchProjectActivity.this, model, 2);
                            }
                        } else if ("3".equalsIgnoreCase(model.getProjectStatus())) {
                        }
                    } else {
                        try {
                            if (!"0".equalsIgnoreCase(model.getProjectStatus())) {
                                if (model != null) {
                                    Intent intent = new Intent(SearchProjectActivity.this, ProDetailActivity.class);
                                    intent.putExtra("info", new Gson().toJson(model));
                                    SearchProjectActivity.this.startActivity(intent);
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onItemChildClick(ViewGroup parent, View v, int position) {
        try {
            if (position < adapter.getData().size()) {
                MyProInfo model = adapter.getItem(position);
                if (model != null) {
                    if(model.getAuth().getAllowJoin()) {
                        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
                        if ("".equalsIgnoreCase(userToken)) {
                            noticeDialog = new PublicNoticeDialog(SearchProjectActivity.this, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    switch (view.getId()) {
                                        case R.id.ll_close:
                                            noticeDialog.dismiss();
                                            break;

                                        case R.id.btn_chancel_notice:
                                            noticeDialog.dismiss();

                                            break;

                                        case R.id.btn_save_notice:
                                            RegisterActivity.start(SearchProjectActivity.this);
                                            noticeDialog.dismiss();
                                            break;

                                    }

                                }
                            }, 1, "提示", "操作此功能，需要请您先注册/登录",
                                    "取消", "确认");
                            noticeDialog.show();
                            return;
                        } else {
                            ApplyProNoticeActivity.start(SearchProjectActivity.this, model.getId(), model.getCreditorId(),
                                    model.getManagerId(), "管理人", model.getContactPhone());
                            return;
                        }

                    }

                    if (v.getId() == R.id.bt_item_bt1) {
                        if (model.getProjectColumnList().getFillingIn()) {
                            ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                            info.setBankruptcyProjectId(model.getId());
                            info.setId(model.getCreditorId());
                            CreateZQOneProjectActivity.start(SearchProjectActivity.this, info,model.getSysAddressId(), model.getContacts(),model.getContactPhone());
                            return;
                        }

                        if (model.getProjectColumnList().getContinueFillingIn()) {
                            getTempData(model.getCreditorId(),model.getId());
                            return;
                        }
                        if ("0".equalsIgnoreCase(model.getProjectStatus())) {
                            //删除 V

                            noticeDialog
                                    = new PublicNoticeDialog(SearchProjectActivity.this, new View.OnClickListener() {
                                @Override
                                public void onClick( View view ) {
                                    String  sendStatus = "";
                                    if (view.getId() == R.id.btn_chancel_notice) {//暂存
                                        sendStatus = "1";
                                        noticeDialog.dismiss();
                                    } else if (view.getId() == R.id.ll_close) {
                                        if (noticeDialog != null && noticeDialog.isShowing())
                                            noticeDialog.dismiss();
                                        return;
                                    } else {//生成
                                        sendStatus = "2";
                                        noticeDialog.dismiss();
                                        DelData(model.getId(), position);
                                    }

                                    noticeDialog.dismiss();

                                }
                            }, 1, "提示", "确定删除项目", "取消", "确定");
                            noticeDialog.show();

                        } else if ("1".equalsIgnoreCase(model.getProjectStatus())) {

                        } else if ("2".equalsIgnoreCase(model.getProjectStatus())) {

                            if (!"".equalsIgnoreCase(model.getJoinId()) && "0".equalsIgnoreCase(model.getJoinType()) && "0".equalsIgnoreCase(model.getAcceptInvitation())) {
                                //拒绝
                                noticeDialog = new PublicNoticeDialog(SearchProjectActivity.this, new View.OnClickListener() {
                                    @Override
                                    public void onClick( View view ) {
                                        String  sendStatus = "";
                                        if (view.getId() == R.id.btn_chancel_notice) {//暂存
                                            sendStatus = "1";
                                            noticeDialog.dismiss();
                                        } else if (view.getId() == R.id.ll_close) {
                                            if (noticeDialog != null && noticeDialog.isShowing())
                                                noticeDialog.dismiss();
                                            return;
                                        } else {//生成
                                            sendStatus = "2";
                                            noticeDialog.dismiss();
                                            accpectOrRefData(model.getId(), "2");
                                        }

                                        noticeDialog.dismiss();

                                    }
                                }, 1, "提示", "确定拒绝邀请?\n拒绝邀请后将导致无法线上申报债权、参与表决等操作！", "取消", "确定");
                                noticeDialog.show();

                            } else {
                                // 管理 V
                                Intent intent = new Intent(SearchProjectActivity.this, ProDetailActivity.class);
                                intent.putExtra("info", new Gson().toJson(model));
                                SearchProjectActivity.this.startActivity(intent);

                            }

                        } else if ("3".equalsIgnoreCase(model.getProjectStatus())) {
                        }

                    } else if (v.getId() == R.id.bt_item_bt2) {

                        if ("0".equalsIgnoreCase(model.getProjectStatus())) {
                            // 管理 V
//                CreateProjectDetailActivity.start(getActivity(), model, 2);
                            EditProjectDetailActivity.start(SearchProjectActivity.this, model, 2);

                        } else if ("1".equalsIgnoreCase(model.getProjectStatus())) {

                        } else if ("2".equalsIgnoreCase(model.getProjectStatus())) {

                            if (!"".equalsIgnoreCase(model.getJoinId()) && "0".equalsIgnoreCase(model.getJoinType()) && "0".equalsIgnoreCase(model.getAcceptInvitation())) {
                                //接收邀请
//                    noticeDialog = new PublicNoticeDialog(getActivity(), onClickListener,
//                            1, "重要须知", "为了保障债权人的合法权益，加入前请再次确认您是相关债权人本人或法定代表人，或是其代理人，并将以本手机号码 188997688976 注册的账户代表相关债权人进行操作，如须变更号码线上操作，请点击变更操作用户，填写操作人的手机号。您也可联系管理人，由管理人协助操作用户加入。",
//                            "确认加入", "变更操作用户");
//                    noticeDialog.show();
                                ApplyProNoticeActivity.start(SearchProjectActivity.this,model.getId(),model.getCreditorId(),model.getSysAddressId(), model.getContacts(),model.getContactPhone());
                            }

                            //需判断是不是自己项目
                            if (model.getCreator().equalsIgnoreCase(BankruptcyApp.loginInfo.getId())) {
                                EditProjectDetailActivity.start(SearchProjectActivity.this, model, 2);
                            }
                        } else if ("3".equalsIgnoreCase(model.getProjectStatus())) {
                        }
                    } else {
                        try {
                            if (!"0".equalsIgnoreCase(model.getProjectStatus())) {
                                if (model != null) {
                                    Intent intent = new Intent(SearchProjectActivity.this, ProDetailActivity.class);
                                    intent.putExtra("info", new Gson().toJson(model));
                                    SearchProjectActivity.this.startActivity(intent);
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.ll_close:
                    noticeDialog.dismiss();
                    break;
                case R.id.btn_chancel_notice:
                    noticeDialog.dismiss();
                    noticelxDialog = new PublicLongNoticeDialog(SearchProjectActivity.this, onClickListener,
                            1, "", "",
                            "", "");
                    noticelxDialog.show();
                    break;
                case R.id.ll_close_lx:
                case R.id.btn_chancel_notice_lx:
                    noticelxDialog.dismiss();
                    break;

                case R.id.btn_save_notice_lx:
                    Boolean flag = noticelxDialog.cb_agree.isChecked();
                    if (flag) {
                        noticelxDialog.dismiss();
//                        CreateZQOneProjectActivity.start(SearchProjectActivity.this);
                    } else {
                        showToast("请同意后再确认");
                    }
                    break;

            }
        }
    };

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            return true;
        }
        return false;
    }


    public void accpectOrRefData(String msgId, String type) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if ("".equalsIgnoreCase(userToken)) {
            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("projectId", msgId)
                .add("opType", type)
                .build();

        String url = Consts.WEBURL_ACCORREF;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
//
//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                getData();
                            }

                        });

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("操作失败：" + object.optString("msg"));
                            }

                        });
                    }


                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            shapeLoadingDialog.dismiss();
                            showToast("请求失败");
                        }

                    });
                }
            }
        });
    }


    public void DelData(String msgId, final int position) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if ("".equalsIgnoreCase(userToken)) {
            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("projectId", msgId)
                .build();

        String url = Consts.WEBURL_DELPRO;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
//
//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                adapter.closeOpenedSwipeItemLayoutWithAnim();
                                adapter.removeItem(position);
                            }

                        });

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("请求失败");
                            }

                        });
                    }


                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            shapeLoadingDialog.dismiss();
                            showToast("请求失败");
                        }

                    });
                }
            }
        });
    }

    public void  getTempData
            (final String creditorId,final String proid)
    {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        Network.getAPIService()
                .fetchCreditorInfoTemp(userToken, creditorId,proid,"1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {
                            int code = json.get("code").getAsInt();

                            if (code != 0) {
                                ToastUtil.showShort("请求数据错误");
                                return;
                            }

                            JsonObject data = json.getAsJsonObject("data");
                            if(data == null ) {
                                ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                                info.setId(creditorId);
                                info.setBankruptcyProjectId(proid);
                                EditZQUserBaseInfoActivity.start(SearchProjectActivity.this, info, 1, 0);
                            }else {

                                ZQUserDetailBaseInfo info = new Gson().fromJson(json.getAsJsonObject("data"), ZQUserDetailBaseInfo.class);
                                info.setId(info.getCreditorId());
                                EditZQUserBaseInfoActivity.start(SearchProjectActivity.this, info, 1, 1);
                            }

//                            info.setBankruptcyProjectId(mProID);


                        }catch (Exception ex) {
                            ex.printStackTrace();
                            ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                            info.setId(creditorId);
                            info.setBankruptcyProjectId(proid);
                            EditZQUserBaseInfoActivity.start(SearchProjectActivity.this, info, 1, 0);

                        }
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });
    }
}
